﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Xms.Abp.Application.Services;
using Xms.Abp.Authorization;
using Xms.Abp.Domain.Repositories;

namespace TenantManagement;

[PermissionsUse(typeof(TenantDomainPermissions))]
public class TenantDomainAppService : XmsCrudAppService<TenantDomain, TenantDomainResult, Guid, TenantDomainPagedParameter, TenantDomainCreateParameter, TenantDomainUpdateParameter>, ITenantDomainAppService
{
    //protected ITenantCacheContext TenantCacheContext => LazyInject<ITenantCacheContext>();
    public TenantDomainAppService(IXmsRepository<TenantDomain, Guid> repository) : base(repository)
    {
    }

    protected override async Task<IQueryable<TenantDomain>> CreateFilteredQueryAsync(TenantDomainPagedParameter input)
    {
        var query = await base.CreateFilteredQueryAsync(input);
        query = query.Where(r => r.TenantId == input.TenantId)
            .WhereIf(!input.Filter.IsNullOrWhiteSpace(), r => r.Name == input.Filter);
        return query;
    }

    //protected override async Task AfterUpdateAsync(TenantDomain entity, TenantDomainUpdateParameter input)
    //{
    //    await RemoveFromCacheAsync(entity);
    //}

    //protected override async Task AfterToggleEnableAsync(TenantDomain entity, bool input)
    //{
    //    await RemoveFromCacheAsync(entity);
    //}

    //protected override async Task AfterDeleteAsync(TenantDomain entity)
    //{
    //    await RemoveFromCacheAsync(entity);
    //}

    //protected virtual async Task RemoveFromCacheAsync(TenantDomain entity)
    //{
    //    var tenant = await LazyInject<IXmsRepository<Tenant, Guid>>().GetAsync(entity.TenantId);
    //    var tenantKey1 = TenantStore.CalculateCacheKey(tenant.Id, null);
    //    var tenantKey2 = TenantStore.CalculateCacheKey(null, tenant.Name);
    //    await TenantCacheContext.Tenants.RefreshManyAsync(new[] { tenantKey1, tenantKey2 });
    //}
}
